<template>
  <BaseDialog class="select-user-dialog" title="选择用户" @confirm="confirm" icon="icons:system-uicons:users" v-model="isShow"
              @close="close">
    <div class="select-user flex" v-loading="loading">
      <div class="flex-1 border-r p-2.5">
        <el-tree
            :data="dataSource"
            show-checkbox
            node-key="id"
            ref="treeRef"
            default-expand-all
            @check-change="checkNode"
        >
          <template #default="{ node, data }">
            <div class="flex">
              <BaseIcon :icon="data.type == 'org'?'icons:clarity:flow-chart-line':'icons:clarity:user-line'" class="mr-1.5"></BaseIcon>
              <span>{{data.name}}</span>
            </div>
          </template>
        </el-tree>
      </div>
      <div class="w-64 p-2.5">
        <el-tag class="mr-2.5" closable @close="delUser(index)" v-for="(item,index) in selectedUser">
          {{ item.realName }}
        </el-tag>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import {nextTick, ref, shallowRef} from "vue";
import {UserModel} from "/@/api/system/model/UserModel";
import {listUserTreeByOrgId} from "/@/api/system/UserApi";
import {TreeModel} from "/@/api/system/model/CommonModel";
import {cloneDeep} from 'lodash-es';
const emit = defineEmits(['confirm'])
const treeRef = ref()
const isShow = ref(false)
const dataSource = ref<TreeModel[]>([])
const selectedUser = ref<UserModel[]>([])
const loading = ref(false)
const callBack = shallowRef<Function>()
const init = async (users: UserModel[] = [],callBackFunction: Function) => {
  callBack.value = callBackFunction
  selectedUser.value = cloneDeep(users)
  isShow.value = true
  loading.value = false
  dataSource.value = await listUserTreeByOrgId("0")
  await nextTick()
  treeRef.value.setCheckedKeys(users.map(res => res.userId))
  loading.value = false

}
const close = () => {
  isShow.value = false
}
const delUser = (index: number) => {
  treeRef.value.setChecked(selectedUser.value[index].userId,false,false)
}
const checkNode = (node,isSelected) => {
  if(node.id < 0){
    return;
  }
  if(isSelected){
    let index = selectedUser.value.findIndex(res=> res.userId == node.id);
    if(index < 0){
      selectedUser.value.push({
        realName: node.name,
        userId: node.id
      })
    }
  }else{
    let index = selectedUser.value.findIndex(res=> res.userId == node.id);
    selectedUser.value.splice(index,1)
  }
}
const confirm = () => {
  callBack.value?.call(this,selectedUser.value)
  close()
}

defineExpose({init})
</script>

<style lang="scss">
.select-user-dialog {
  .select-user {
    height: calc(100vh - 500px);
  }

  .el-dialog__body {
    padding: 0px;
  }
}

</style>